package csu.jpetstore.jpetstore.controller;


import csu.jpetstore.jpetstore.dto.UserDTO;
import csu.jpetstore.jpetstore.dto.UserSignInDTO;
import csu.jpetstore.jpetstore.result.Result;
import csu.jpetstore.jpetstore.result.ResultFactory;
import csu.jpetstore.jpetstore.service.UserAuthsService;
import org.apache.shiro.SecurityUtils;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresGuest;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;
@CrossOrigin
@RestController
@RequestMapping(value = "/api")
public class TokenController {

    @Autowired
    UserAuthsService userAuthsService;

    @RequiresUser
    @GetMapping("/token")
    public Result authentication(){
        return ResultFactory.getSuccess("身份认证成功",null);
    }

    @RequiresGuest
    @RequestMapping(value = "/token",method = RequestMethod.POST)
    public Result login(@RequestBody UserSignInDTO user){
        String username = HtmlUtils.htmlEscape(user.getUsername());
        Subject subject = SecurityUtils.getSubject();
        String userId = userAuthsService.getUserAuthByUsername(username).getUser().getId();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userId, user.getPassword());
        if (user.getRememberMe().equals("yes"))
            usernamePasswordToken.setRememberMe(true);
        try {
            subject.login(usernamePasswordToken);
            return ResultFactory.getSuccess("登录成功",userId);
        } catch (AuthenticationException e) {
            String message = "账号密码错误";
            return ResultFactory.getFail(message, null);
        }
    }


    @RequiresUser
    @DeleteMapping("/token")
    public Result logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        String message = "成功登出";
        return ResultFactory.getSuccess(message,null);
    }
}
